<?php
/**
 * Created by PhpStorm.
 * User: 大伟PHPer
 * Date: 2019/5/12
 * Time: 1:25 PM
 */
$obj = new PDO('mysql:host=localhost;dbname=blog_db','root','root');
$c = 0;
$obj->beginTransaction();
    // 第一次请求与第二次请求返回不同数据
    $data = reqData();
    $condition = $data['condition'];
    $forUpdate = $data['req'] == 1 ? ' for update' : ' for update ';
    //$forUpdate = $data['req'] == 1 ? ' for update' : ' ';
    $sql = "select * from test_user where {$condition}  {$forUpdate}";
    echo 'sql语句：' . $sql . '<br>';
    echo '开始等待<br>';
    $waitBeforeTime = time();
    $result = $obj->query($sql)->fetch(PDO::FETCH_ASSOC);
    $waitAfterTime = time();
    echo '等待了 ' . ($waitAfterTime - $waitBeforeTime) . ' 秒后才开始处理<br>';
    // 模拟逻辑处理时间
    sleep(3);
    echo "获取到的数据：";
    print_r($result);
    echo '<br>';
    echo '执行完毕';
$obj->commit();

/**
 * 为先后两次请求提供不同数据
 */
function reqData(){
    $data = [
        'condition' => null,
        'req' => null,
    ];
    $fileName = 'status.log';
    if(file_exists($fileName) && file_get_contents($fileName) == 1){
        file_put_contents($fileName,'2');
        $req = 2;
    } else {
        //第一次请求
        $req = 1;
        file_put_contents($fileName,'1');
    }
    $data['req'] = $req;
    if($req == 1){
        //$data['condition'] = ' id = 11';
        $data['condition'] = 'username = "nicaiyonghu" and id = 1019';
    } else {
        //$data['condition'] = ' id = 10';
        $data['condition'] = 'id = 1019';
    }
    return $data;
}
